<template>
  <a-row :gutter="24" class="search-row">
    <x-card>
      <div slot="content" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item
                label="隐患单位"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-tree-select
                  allowClear
                  showSearch
                  style="scroll:true"
                  tree-node-filter-prop="title"
                  v-model="queryParam.OrganizationName"
                  :treeData="QHSEOrganizationTree"
                  v-if="QHSEOrganizationTree.length"
                  @change="handleOrganizationSelectChange"
                  :defaultExpandAll="true"
                  :defaultExpandedKeys="defaultExpandedKeys"
                  :replaceFields="replaceFields"
                  ref="tree"
                  placeholder="请选择隐患单位"
                  :title="queryParam.OrganizationName" />
              </a-form-item>
            </a-col>
            <a-col :span="7" >
              <a-form-item
                label="检查时间"
                :labelCol="{ style: 'width:115px' }"
                :wrapperCol="wrapperCol"
              >
                <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange1" :style="{width: '50%'}" v-model="TimeOn1"/>
                <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange2" :style="{width: '50%'}" v-model="TimeEnd1"/>
              </a-form-item>
            </a-col>
            <a-col :span="7" >
              <a-form-item
                label="对比时间"
                :labelCol="{ style: 'width:115px' }"
                :wrapperCol="wrapperCol"
              >
                <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange3" :style="{width: '50%'}" v-model="TimeOn2"/>
                <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange4" :style="{width: '50%'}" v-model="TimeEnd2"/>
              </a-form-item>
            </a-col>
            <a-col :span="3" style="margin-bottom: 3px;">
              <a-button type="primary" @click="handleClick" :loading="saving">查询</a-button>
              <a-button type="default" @click="exportToExcel" style="margin-left: 8px;">导出</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-row :gutter="48" class="search-row">
      <a-col :span="24">
        <a-divider orientation="left" style="font-weight: bold; margin-bottom: -2px;margin-top: -2px"> 隐患数量分析
        </a-divider>
        <a-card style="overflow-y: auto;" :bordered="false">
          <a-row style="width: 100%; height: 300px; margin-top: 20px">
            <a-progress
              v-if="batchExportLoading1"
              :percent="exportProgress1"
              status1="active"
            />
            <a-col :span="24">
              <div id="bar-chart-container1" style="width: 100%; height: 600px;"></div>
            </a-col>
          </a-row>
          <a-row style="width: 100%; height: 400px;">
            <a-progress
              v-if="batchExportLoading"
              :percent="exportProgress"
              status="active"
            />
            <a-col :span="24">
              <a-table
                bordered
                :columns="columns"
                :dataSource="loadData"
                :alert="false"
                :pagination="false"
                :rowKey="(record, index) => index"
              >
              </a-table>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </a-row>
</template>
<script>
import { STable, XCard, XDown } from '@/components'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import moment from 'moment'
import { getQHSEStartTabelSelfDangerCheckCount, getQHSEGetTabelSelfDangerCheckCountStatus, getQHSETakeTableSelfDangerCheckCount, getQHSEStartCompareDangerCheckCount, getQHSEGetCompareDangerCheckCountStatus, getQHSETakeCompareDangerCheckCount } from '@/api/modular/system/QHSEDanSearch'
import { mapGetters } from 'vuex'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx'
export default {
    components: {
      XDown,
      XCard,
      STable
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        defaultExpandedKeys: [],
        QHSEOrganizationTree: [],
        task: {
          Id: ''
        },
        task1: {
          Id: ''
        },
        secondOraName: {
            id: ''
        },
        exportProgress: 0,
        status: '',
        batchExportLoading: false,
        exportProgress1: 0,
        status1: '',
        batchExportLoading1: false,
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'workflowId',
          value: 'id',
          parentId: 'parentId'
        },
        queryParam: {
          TimeOn1: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd1: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
          TimeOn2: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd2: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
          OrganizationName: '川庆钻探',
          OrganizationId: '00'
        },
        TimeEnd1: moment(new Date(), 'YYYY-MM-DD'),
        TimeOn1: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
        TimeEnd2: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
        TimeOn2: moment(new Date(), 'YYYY-MM-DD').subtract(2, 'months'),
        saving: false,
        // 表头
        columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '单位名称',
          dataIndex: 'organizationName',
          style: {
            fontSize: '200px'
          }
        },
        {
          title: '',
          children: [
            {
              title: '自查数',
              dataIndex: 'value1'
            },
            {
              title: '监督纠察数量',
              dataIndex: 'value2'
            },
            {
              title: '合计',
              dataIndex: 'total1',
              customRender: function(text) {
                return <span style={{ color: '#e6b422', fontWeight: 'bold' }}>{text}</span>
              }
            }
           ]
         },
         {
          title: '',
          children: [
            {
              title: '自查数',
              dataIndex: 'value3'
            },
            {
              title: '监督纠察数量',
              dataIndex: 'value4'
            },
            {
              title: '合计',
              dataIndex: 'total2',
                customRender: function(text) {
                  return <span style={{ color: '#e6b422', fontWeight: 'bold' }}>{text}</span>
                }
            }
           ]
         },
         {
          title: '总数增幅',
          dataIndex: 'growthRate'
         }
        ],
        loadData: [],
        dangerCheckData: []
        }
    },
    computed: {
      ...mapGetters(['userInfo']),
      computedTimeRange1() {
        return `${this.TimeOn1.format('YYYY-MM-DD')} - ${this.TimeEnd1.format('YYYY-MM-DD')}`
      },
      computedTimeRange2() {
        return `${this.TimeOn2.format('YYYY-MM-DD')} - ${this.TimeEnd2.format('YYYY-MM-DD')}`
      }
    },
    created() {
      this.getQHSEOrganizationTree()
    },
    methods: {
        // 更改隐患单位
        handleOrganizationSelectChange(val, opt, extra) {
          if (extra.triggerNode === undefined) {
            this.queryParam.OrganizationName = null
            this.queryParam.OrganizationId = null
          } else {
            const option = extra.triggerNode._props.title
            this.queryParam.OrganizationName = option
            this.queryParam.OrganizationId = extra.triggerNode._props.value
          }
        },
        // 组织树
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
        })
      },
      onChange1(date, dateString) {
        // console.log(dateString, date)
        if (this.queryParam.TimeEnd1 && dateString) {
          if (dateString > this.queryParam.TimeEnd1) {
            this.$message.error('检查开始时间不能晚于结束时间')
            this.TimeEnd1 = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn1 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn1 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd1 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeOn1 = dateString
          }
        } else {
          this.queryParam.TimeOn1 = dateString
        }
        // console.log('TimeOn1', this.queryParam.TimeOn1)
      },
      onChange2(date, dateString) {
        if (this.queryParam.TimeOn1 && dateString) {
          if (this.queryParam.TimeOn1 > dateString) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd1 = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn1 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn1 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd1 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeEnd1 = dateString + 'T' + moment().format('23:59:59')
          }
        } else {
          this.queryParam.TimeEnd1 = dateString + 'T' + moment().format('23:59:59')
        }
        // console.log('TimeEnd1', this.queryParam.TimeEnd1)
      },
      onChange3(date, dateString) {
        // console.log(dateString, date)
        if (this.queryParam.TimeEnd2 && dateString) {
          if (dateString > this.queryParam.TimeEnd2) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd2 = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn2 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn2 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd2 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeOn2 = dateString
          }
        } else {
          this.queryParam.TimeOn2 = dateString
        }
        // console.log('TimeOn2', this.queryParam.TimeOn2)
      },
      onChange4(date, dateString) {
        if (this.queryParam.TimeOn2 && dateString) {
          if (this.queryParam.TimeOn2 > dateString) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd2 = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn2 = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn2 = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd2 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeEnd2 = dateString + 'T' + moment().format('23:59:59')
          }
        } else {
          this.queryParam.TimeEnd2 = dateString + 'T' + moment().format('23:59:59')
        }
        // console.log('TimeEnd2 ', this.queryParam.TimeEnd2)
      },
        handleClick() {
          if ((!this.TimeOn1 && !this.TimeEnd1) || (this.TimeOn1 && this.TimeEnd1) && (!this.TimeOn2 && !this.TimeEnd2) || (this.TimeOn2 && this.TimeEnd2)) {
            // console.log('query', this.queryParam)
            this.columns[2].title = `${this.TimeOn1.format('YYYY-MM-DD')} - ${this.TimeEnd1.format('YYYY-MM-DD')}`
            this.columns[3].title = `${this.TimeOn2.format('YYYY-MM-DD')} - ${this.TimeEnd2.format('YYYY-MM-DD')}`
            // 后端方法
            this.select()
            this.loadTableData()
          } else {
            this.$message.warning('请填写完整的查询条件')
          }
        },
        exportToExcel() {
            // 设置导出的数据，手动调整字段名称
            const exportData = this.loadData.map((item, index) => ({
                单位名称: item.organizationName,
                检查时间自查数: item.value1,
                检查时间监督查纠数量: item.value2,
                检查时间合计: item.total1,
                对比时间自查数: item.value3,
                对比时间监督纠察数量: item.value4,
                对比时间合计: item.total2,
                总数增幅: item.growthRate
            }))
            // 创建工作表和工作簿
            const ws = XLSX.utils.json_to_sheet(exportData)
            const wb = XLSX.utils.book_new()
            XLSX.utils.book_append_sheet(wb, ws, '隐患查纠数量对比')
            // 导出 Excel 文件，文件名带当前日期
            XLSX.writeFile(wb, `隐患查纠数量对比_${moment().format('YYYYMMDD')}.xlsx`)
        },
        select() {
            // 后端方法
            this.saving = true
            this.batchExportLoading = true
        getQHSEStartTabelSelfDangerCheckCount(this.queryParam).then((res) => {
          // console.log('res.taskId', res.taskId)s
          this.task.Id = res.taskId
        })
        this.exportProgress = 0 // 重置进度
        setInterval(() => {
          if (this.exportProgress < 90) { // 进度最高到 90%，剩下的 10% 在下载完成时更新
            this.exportProgress += 10
          }
        }, 500)
           // 每 5 秒轮询状态
        const statusInterval = setInterval(() => {
          getQHSEGetTabelSelfDangerCheckCountStatus(this.task).then((res) => {
            this.status = res.status
           if (this.status === 'completed') {
             // 清除进度定时器，确保定时器被清除
             clearInterval(statusInterval)
             // 开始执行 getExportToExcel
             getQHSETakeTableSelfDangerCheckCount(this.task).then((res) => {
               this.loadData = res.data.compare
               this.exportProgress += 10
               this.batchExportLoading = false
              //  console.log('this.loadData', this.loadData)
             })
             .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
           }
          }).catch(error => {
          console.error('状态获取失败:', error)
          clearInterval(statusInterval) // 出现错误时，也要清除定时器
          // clearInterval(interval)
         })
       }, 5000)
        },
        loadTableData() {
        this.batchExportLoading1 = true
        getQHSEStartCompareDangerCheckCount(this.queryParam).then((res) => {
          // console.log('res.taskId', res.taskId)s
          this.task1.Id = res.taskId
        })
        this.exportProgress1 = 0 // 重置进度
        setInterval(() => {
          if (this.exportProgress1 < 90) { // 进度最高到 90%，剩下的 10% 在下载完成时更新
            this.exportProgress1 += 10
          }
        }, 500)
           // 每 5 秒轮询状态
        const statusInterval = setInterval(() => {
          getQHSEGetCompareDangerCheckCountStatus(this.task1).then((res) => {
            this.status1 = res.status
           if (this.status1 === 'completed') {
             // 清除进度定时器，确保定时器被清除
             clearInterval(statusInterval)
             // 开始执行 getExportToExcel
             getQHSETakeCompareDangerCheckCount(this.task1).then((res) => {
               this.renderMulBarChart(res.data.compare, 'bar-chart-container1', 'bar')
               this.exportProgress1 += 10
               this.batchExportLoading1 = false
              //  console.log('this.loadData', this.loadData)
             })
             .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
           }
          }).catch(error => {
          console.error('状态获取失败:', error)
          this.loading2 = false
          clearInterval(statusInterval) // 出现错误时，也要清除定时器
          // clearInterval(interval)
         })
       }, 5000)
          },
        renderMulBarChart(data, containerId, chartType) {
        const barChartContainer = document.getElementById(containerId)
        const barChart = echarts.init(barChartContainer)
        if (data.item === undefined) {
          return
        }
        const barChartData = data.item
        console.log('data.item', data.item)
        const barChartOption = {
          title: {
            text: '',
            textStyle: {
              fontWeight: 'bold',
              fontSize: 20
            },
            left: 'center' // 标题水平居中
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            orient: 'horizontal',
            x: 'center',
            y: 'bottom',
            textStyle: {
              fontSize: 16
            }
          },
          grid: {
            containLabel: true,
            top: 60
          },
          xAxis: {
            type: 'category'
          },
          yAxis: {
            type: 'value'
          },
          series: []
        }
        const headerRow = barChartData[0]
        for (var i = 1; i < headerRow.length; i++) {
          var dataObj = {
            name: headerRow[i],
            type: 'bar',
            data: barChartData.slice(1).map(row => row[i]),
            label: {
                show: true,
                position: 'top',
                formatter: function (params) {
                  // 根据seriesIndex来决定是否显示标签
                  if (params.seriesIndex % 1 === 0) {
                    return params.value
                  } else {
                    return ''
                  }
                }
              }
          }
          barChartOption.series.push(dataObj)
        }
        barChartOption.title.text = barChartData[0][0]
        // 超过13个专业竖着显示横坐标
        if (barChartData.length > 13) {
            barChartOption.xAxis.axisLabel = {
              formatter: function (value) {
                return value.split('').join('\n') // 在每个字符之间添加换行符
              },
              fontSize: 14
          }
        } else {
          barChartOption.xAxis.axisLabel = {
            interval: 0,
            formatter: null,
            fontSize: 14 // 设置较大的字体大小
          }
        }
        barChartOption.xAxis.data = barChartData.slice(1).map(row => row[0])
        if (barChartData.length > 0) {
          barChart.setOption(barChartOption)
        }
        barChart.setOption(barChartOption)
      }
    }
}
</script>

<style lang="less" scoped>
/deep/.ant-table-tbody tr:last-child
 {
  background-color:#f5f5f5d6;
 }

</style>
